package org.yyds;

import org.apache.commons.configuration2.Configuration;
import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.sftp.server.SftpSubsystemFactory;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;

public class SFTPServer {

    public static void main(String[] args) {
        Configuration config = ConfigLoader.getConfig();

        int port = config.getInt("sftpserver.port");
        String sftpserverUser = config.getString("sftpserver.username");
        String sftpserverPassword = config.getString("sftpserver.password");
        String homeDir = config.getString("sftpserver.home-dir");

        SshServer sshd = SshServer.setUpDefaultServer();
        sshd.setPort(port);

        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")));

        // 设置密码验证器
        sshd.setPasswordAuthenticator((username, password, session) -> sftpserverPassword.equals(password));

        // 设置SFTP根目录和用户家目录
        VirtualFileSystemFactory virtualFileSystemFactory = new VirtualFileSystemFactory();
        virtualFileSystemFactory.setUserHomeDir(sftpserverUser, Paths.get(homeDir));
        sshd.setFileSystemFactory(virtualFileSystemFactory);

        // 设置SFTP子系统
        sshd.setSubsystemFactories(Arrays.asList(new SftpSubsystemFactory()));

        try {
            sshd.start();
            System.out.println("SFTP服务器已启动...");
            System.out.printf("port：%s, susername：%s, password：%s, homeDir：%s\n", port, sftpserverUser, sftpserverPassword, homeDir);
            new CountDownLatch(1).await();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
